package com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.HddcGeologicalsvyplanninglineRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.repository.HddcWyGeologicalsvyplanninglineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.repository.HddcWyGeologicalsvyplanninglineRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.repository.entity.HddcWyGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.service.HddcWyGeologicalsvyplanninglineService;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPlanningLine.viewobjects.HddcWyGeologicalsvyplanninglineQueryParams;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author zhangping
 * @date 2020-12-01
 */
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class HddcWyGeologicalsvyplanninglineServiceImpl implements HddcWyGeologicalsvyplanninglineService {

    @Autowired
    private HddcWyGeologicalsvyplanninglineRepository hddcWyGeologicalsvyplanninglineRepository;
    @Autowired
    private HddcWyGeologicalsvyplanninglineNativeRepository hddcWyGeologicalsvyplanninglineNativeRepository;
    @Autowired
    private HddcGeologicalsvyplanninglineRepository hddcGeologicalsvyplanninglineRepository;
    @Value("${image.localDir}")
    private String localDir;
    @Value("${image.urlPre}")
    private String urlPre;

    @Override
    public JSONObject queryHddcWyGeologicalsvyplanninglines(HddcWyGeologicalsvyplanninglineQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeologicalsvyplanninglineEntity> hddcWyGeologicalsvyplanninglinePage = this.hddcWyGeologicalsvyplanninglineNativeRepository.queryHddcWyGeologicalsvyplanninglines(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeologicalsvyplanninglinePage);
        return jsonObject;
    }


    @Override
    public HddcWyGeologicalsvyplanninglineEntity getHddcWyGeologicalsvyplanningline(String uuid) {
        HddcWyGeologicalsvyplanninglineEntity hddcWyGeologicalsvyplanningline = this.hddcWyGeologicalsvyplanninglineRepository.findById(uuid).orElse(null);
        return hddcWyGeologicalsvyplanningline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvyplanninglineEntity    saveHddcWyGeologicalsvyplanningline(HddcWyGeologicalsvyplanninglineEntity hddcWyGeologicalsvyplanningline) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeologicalsvyplanningline.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyGeologicalsvyplanningline.getCreateUser())){
            hddcWyGeologicalsvyplanningline.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeologicalsvyplanningline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeologicalsvyplanningline.setIsValid("1");

        HddcGeologicalsvyplanninglineEntity hddcGeologicalsvyplanninglineEntity = new HddcGeologicalsvyplanninglineEntity();
        BeanUtils.copyProperties(hddcWyGeologicalsvyplanningline, hddcGeologicalsvyplanninglineEntity);
        hddcGeologicalsvyplanninglineEntity.setExtends4(hddcWyGeologicalsvyplanningline.getTown());
        hddcGeologicalsvyplanninglineEntity.setExtends5(String.valueOf(hddcWyGeologicalsvyplanningline.getLon()));
        hddcGeologicalsvyplanninglineEntity.setExtends6(String.valueOf(hddcWyGeologicalsvyplanningline.getLat()));
        this.hddcGeologicalsvyplanninglineRepository.save(hddcGeologicalsvyplanninglineEntity);

        this.hddcWyGeologicalsvyplanninglineRepository.save(hddcWyGeologicalsvyplanningline);
        return hddcWyGeologicalsvyplanningline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvyplanninglineEntity updateHddcWyGeologicalsvyplanningline(HddcWyGeologicalsvyplanninglineEntity hddcWyGeologicalsvyplanningline) {
        HddcWyGeologicalsvyplanninglineEntity entity = hddcWyGeologicalsvyplanninglineRepository.findById(hddcWyGeologicalsvyplanningline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeologicalsvyplanningline);
        hddcWyGeologicalsvyplanningline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeologicalsvyplanningline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeologicalsvyplanninglineRepository.save(hddcWyGeologicalsvyplanningline);
        return hddcWyGeologicalsvyplanningline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeologicalsvyplanninglines(List<String> ids) {
        List<HddcWyGeologicalsvyplanninglineEntity> hddcWyGeologicalsvyplanninglineList = this.hddcWyGeologicalsvyplanninglineRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcWyGeologicalsvyplanninglineList) && hddcWyGeologicalsvyplanninglineList.size() > 0) {
            for (HddcWyGeologicalsvyplanninglineEntity hddcWyGeologicalsvyplanningline : hddcWyGeologicalsvyplanninglineList) {
                this.hddcWyGeologicalsvyplanninglineRepository.delete(hddcWyGeologicalsvyplanningline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeologicalsvyplanningline(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeologicalsvyplanninglineNativeRepository.queryHddcWyGeologicalsvyplanningline(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeologicalsvyplanninglineEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeologicalsvyplanninglineEntity> list = hddcWyGeologicalsvyplanninglineRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    /**
     * 图片批量上传
     * @param multipartFiles
     * @param type
     * @return
     * @throws IOException
     */
    @Override
    public String uploadPic(MultipartFile[] multipartFiles, String type) throws IOException {
        /*List<String> sbList = new ArrayList<>();*/
        StringBuilder sb = new StringBuilder();
        if (multipartFiles != null && multipartFiles.length > 0) {
            for (int i = 0; i < multipartFiles.length; i++) {
                MultipartFile file = multipartFiles[i];
                // 1.判断是否为图片 abc.jpg
                String fileName = file.getOriginalFilename();
                // 使用正则表达式进行判断
                if (!fileName.matches("^.*(jpg|png|gif)$")) { // . 代表任意的字符 * 代表有任意多个 的
                    List<String> msgList = new ArrayList<>();
                    // 表示不是图片
                    msgList.add("第" + (i + 1) + "张不是图片");
                    //return msgList;
                    throw new RuntimeException("第" + (i + 1) + "张不是图片");
                }
                try {
                    /**
                     * ImageIO是javax下面的一个工具类
                     */
                    // 2.判断是否为恶意程序 uploadFile.getInputStream() 文件流
                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                    // 3.获取图片宽度和高度 (图片宽高为 0 ,则图片是假的图片)
                    int height = bufferedImage.getHeight();
                    int width = bufferedImage.getWidth();
                    if (height == 0 || width == 0) {// 假图片
                        List<String> msgList = new ArrayList<>();
                        msgList.add("第" + (i + 1) + "张是假图片");
                        //return msgList;
                        throw new RuntimeException("第" + (i + 1) + "张不是图片");
                    }
                    // 4.准备文件存储的路径()
                    //String localDir = "D:/IdeaProjects/fwsjcj/src/main/webapp/static/image"; // 本地文件夹
                    // 5.实现分文件存储 yyyy/MM/dd 以 天 为单位 分文件
                    String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
                    // 6.形成保存图片的文件夹 d:/file/yyyy/MM/dd (文件存储的根目录)
                    String typePath="";
                    if ("1".equals(type)) {
                        typePath="地质调查规划路线-线";
                        //picDir = localDir + "/" + "地质调查规划路线-线" + "/" + dateDir;
                    }else
                    if("2".equals(type)){
                        typePath="地质调查规划点-点";
                        //picDir = localDir + "/" + "地质调查规划点-点" + "/" + dateDir;
                    }else
                    if("3".equals(type)){
                        typePath="断层观测点-点";
                        //picDir = localDir + "/" + "断层观测点-点" + "/" + dateDir;
                    }else
                    if("4".equals(type)){
                        typePath="地质地貌调查观测点-点";
                        //picDir = localDir + "/" + "地质地貌调查观测点-点" + "/" + dateDir;
                    }else
                    if("5".equals(type)){
                        typePath="地质调查路线-线";
                        //picDir = localDir + "/" + "地质调查路线-线" + "/" + dateDir;
                    }else
                    if("6".equals(type)){
                        typePath="地质调查观测点-点";
                        //picDir = localDir + "/" + "地质调查观测点-点" + "/" + dateDir;
                    }else
                    if("7".equals(type)){
                        typePath="地层观测点-点";
                        //picDir = localDir + "/" + "地层观测点-点" + "/" + dateDir;
                    }else
                    if("8".equals(type)){
                        typePath="探槽-点";
                        //picDir = localDir + "/" + "探槽-点" + "/" + dateDir;
                    }else
                    if("9".equals(type)){
                        typePath="微地貌测量线-线";
                        //picDir = localDir + "/" + "微地貌测量线-线" + "/" + dateDir;
                    }else
                    if("10".equals(type)){
                        typePath="微地貌测量点-点";
                        //picDir = localDir + "/" + "微地貌测量点-点" + "/" + dateDir;
                    }else
                    if("11".equals(type)){
                        typePath="微地貌测量面-面";
                        //picDir = localDir + "/" + "微地貌测量面-面" + "/" + dateDir;
                    }else
                    if("12".equals(type)){
                        typePath="微地貌面测量切线-线";
                        //picDir = localDir + "/" + "微地貌面测量切线-线" + "/" + dateDir;
                    }else
                    if("13".equals(type)){
                        typePath="微地貌测量采样点-点";
                        //picDir = localDir + "/" + "微地貌测量采样点-点" + "/" + dateDir;
                    }else
                    if("14".equals(type)){
                        typePath="微地貌测量基站点-点";
                        //picDir = localDir + "/" + "微地貌测量基站点-点" + "/" + dateDir;
                    }else
                    if("15".equals(type)){
                        typePath="钻孔-点";
                        //picDir = localDir + "/" + "钻孔-点" + "/" + dateDir;
                    }else
                    if("16".equals(type)){
                        typePath="采样点-点";
                        //picDir = localDir + "/" + "采样点-点" + "/" + dateDir;
                    }else
                    if("17".equals(type)){
                        typePath="地球物理测线-线";
                        //picDir = localDir + "/" + "地球物理测线-线" + "/" + dateDir;
                    }else
                    if("18".equals(type)){
                        typePath="地球物理测点-点";
                        //picDir = localDir + "/" + "地球物理测点-点" + "/" + dateDir;
                    }else
                    if("19".equals(type)){
                        typePath="地球化学探测测线-线";
                        //picDir = localDir + "/" + "地球化学探测测线-线" + "/" + dateDir;
                    }else
                    if("20".equals(type)){
                        typePath="地球化学探测测点-点";
                        //picDir = localDir + "/" + "地球化学探测测点-点" + "/" + dateDir;
                    }else
                    if("21".equals(type)){
                        typePath="火山口-点";
                        //picDir = localDir + "/" + "火山口-点" + "/" + dateDir;
                    }else
                    if("22".equals(type)){
                        typePath="熔岩流-面";
                        //picDir = localDir + "/" + "熔岩流-面" + "/" + dateDir;
                    }else
                    if("23".equals(type)){
                        typePath="火山采样点-点";
                        //picDir = localDir + "/" + "火山采样点-点" + "/" + dateDir;
                    }else
                    if("24".equals(type)){
                        typePath="火山调查观测点-点";
                        //picDir = localDir + "/" + "火山调查观测点-点" + "/" + dateDir;
                    }
                    String picDir = localDir + "/" + typePath + "/" + dateDir;;
                    // 7.生成文件夹
                    File picFile = new File(picDir); // 文件夹的文件执行
                    if (!picFile.exists()) { // 文件夹不存在 就创建文件夹
                        picFile.mkdirs();
                    }
                    // 8.重命名上传的文件名字 (避免重名)
                   // String uuid = UUID.randomUUID().toString().replace("-", ""); // asa22exac-adsfafadsf-3fddsfds
                    // 生成随机数
                    //int randomNum = new Random().nextInt(999); // 生成随机数 (0-999)
                    String uuid = UUID.randomUUID().toString();
                    // 获取文件的后缀名
                    String fileType = fileName.substring(fileName.lastIndexOf("."));//获取后缀名
                    //获取的时分秒毫秒
                    String hHmmssSSS = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmssSSS"));

                    String realFileName = uuid + "_" + hHmmssSSS + "_000" + (i + 1) + fileType;
                    // 拼文件名
                  //  String realFileName = uuid + randomNum + fileType; // 真实的文件名称
                    // 9生成文件的本地磁盘的路径 d:/file/yyyy/MM/dd/wqrwadasfiuoew800.jpg
                    String localPath = picDir + "/" + realFileName;
                    byte[] file2byte = File2byte(file.getInputStream());
                    OutputStream os = new FileOutputStream(localPath);
                    os.write(file2byte);
                    os.close();
                   // localPath = localPath.replace("/", "\\");
                    // 10实现文件的上传
                   // multipartFiles[i].transferTo(new File(localPath));

                    // 11添加文件的宽度,高度 需要返回
                    //result.setHeight(height + "");
                    //result.setWidth(width + "");

                    // 12准备文件的虚拟路径
                    // http://image.jt.com/file/2018/05/07/radweedwsaf210.jpg
                    //String urlPre = "http://10.33.0.164:8081/static/image";

                    String urlPath = urlPre +"/"+typePath+"/" + dateDir + "/" + realFileName;

                    sb.append(urlPath);
                    sb.append(",");
                } catch (Exception e) { // 不是图片会抛异常
                    e.printStackTrace();
                    //result.setError(1); // 表示为恶意程序
                    //sbList.add("第" + (i + 1) + "张是恶意程序");
                    //return stringList;
                    throw new RuntimeException("第" + (i + 1) + "张不是图片");
                }
            }
        }
        if(sb.toString().length()==0){
            return "";
        }
        return sb.toString().substring(0,sb.toString().length()-1);
    }

    public static byte[] File2byte(InputStream fis) {
        byte[] buffer = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 获取地图上所有的点
     * @param userId
     * @param isValid
     * @return
     */
    @Override
    public List<HddcWyGeologicalsvyplanninglineEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyGeologicalsvyplanninglineEntity> list = hddcWyGeologicalsvyplanninglineRepository.findAllByCreateUserAndIsValid(userId, isValid);
        return list;
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeologicalsvyplanninglineEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvyplanninglineRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeologicalsvyplanninglineEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvyplanninglineRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeologicalsvyplanninglineEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvyplanninglineRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeologicalsvyplanninglineEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvyplanninglineRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }
}